package com.izocen.rules.assembler.operator.chain;

import org.apache.commons.lang.StringUtils;

import com.izocen.rules.common.EasyStringUtils;

public abstract class AbstractOperator {
	
	public AbstractOperator(String type) {
		this.operatorType = type;
	}
	
	protected AbstractOperator nextOperator;
	
	protected String operatorType;
	
	
	public void setNextOperator(AbstractOperator operator) {
		this.nextOperator = operator;
	}
	
	protected void handlerRequest(String operatorExpress){

    }
	
	public String handle(String message) throws Exception{
		  boolean match = EasyStringUtils.matchOperator(message);
		  if(!match) {
			  throw new Exception("表达式有错误:"+message +" |  【建议检查】: { 判断语句判断符号两边应该有两个空格，例如: alarm in ['1',2]  }");
		  }
	      if(StringUtils.contains(message, " "+this.operatorType+" ")) {
	    	  //message = this.template(message);
	    	  message = format(message);
	    	  return message;
	      }
	      if(nextOperator !=null){
	    	 return nextOperator.handle(message);
	      }
	      return null;
	   }
	
	abstract protected String format(String message) throws Exception;
	
	public  String templateSimpleParam(String message) throws Exception{
		String[] arr = message.split(this.operatorType);
		if(arr == null || arr.length != 2) {
			throw new Exception("表达式:["+message+"]格式不对请检查");
		}
		String key = "${"+arr[0].trim()+"}";
		String val = ""+arr[1].trim()+"";
		return key + " "+ this.operatorType + " " + val;
	}

}
